package com.link.linkupjavaweb.controller.user;

import com.link.linkupjavaweb.common.Constants;
import com.link.linkupjavaweb.common.Result;
import com.link.linkupjavaweb.dto.GameResultDTO;
import com.link.linkupjavaweb.entity.GameRecord;
import com.link.linkupjavaweb.entity.User;
import com.link.linkupjavaweb.service.GameService;
import com.link.linkupjavaweb.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * 游戏Controller
 */
@Controller
@RequestMapping("/user/game")
public class GameController {
    
    @Autowired
    private GameService gameService;
    
    @Autowired
    private ItemService itemService;
    
    /**
     * 跳转到游戏选择页面
     */
    @GetMapping("/select")
    public String selectGame(HttpSession session, Model model) {
        User user = (User) session.getAttribute(Constants.SESSION_USER);
        if (user == null) {
            return "redirect:/user/login";
        }
        model.addAttribute("user", user);
        return "user/game/select";
    }
    
    /**
     * 跳转到单机游戏页面
     */
    @GetMapping("/single")
    public String singleGame(@RequestParam(defaultValue = "normal") String mode, 
                            HttpSession session, 
                            Model model) {
        User user = (User) session.getAttribute(Constants.SESSION_USER);
        if (user == null) {
            return "redirect:/user/login";
        }
        model.addAttribute("user", user);
        model.addAttribute("mode", mode);
        return "user/game/single";
    }
    
    /**
     * 保存游戏结果
     */
    @PostMapping("/save")
    @ResponseBody
    public Result<GameRecord> saveGameResult(@RequestBody GameResultDTO resultDTO, HttpSession session) {
        try {
            User user = (User) session.getAttribute(Constants.SESSION_USER);
            if (user == null) {
                return Result.error("请先登录");
            }
            
            GameRecord record = gameService.saveGameRecord(user.getId(), resultDTO);
            
            // 更新session中的用户信息
            User updatedUser = (User) session.getAttribute(Constants.SESSION_USER);
            if (updatedUser != null) {
                updatedUser.setTotalScore(updatedUser.getTotalScore() + resultDTO.getScore());
                updatedUser.setGameCount(updatedUser.getGameCount() + 1);
                if (resultDTO.getMaxCombo() > updatedUser.getMaxCombo()) {
                    updatedUser.setMaxCombo(resultDTO.getMaxCombo());
                }
                session.setAttribute(Constants.SESSION_USER, updatedUser);
            }
            
            return Result.success("游戏记录保存成功", record);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("保存失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取用户游戏记录
     */
    @GetMapping("/records")
    @ResponseBody
    public Result<List<GameRecord>> getGameRecords(HttpSession session) {
        try {
            User user = (User) session.getAttribute(Constants.SESSION_USER);
            if (user == null) {
                return Result.error("请先登录");
            }
            
            List<GameRecord> records = gameService.getUserGameRecords(user.getId(), 10);
            return Result.success(records);
        } catch (Exception e) {
            return Result.error("获取记录失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取用户游戏统计
     */
    @GetMapping("/stats")
    @ResponseBody
    public Result<Object> getGameStats(HttpSession session) {
        try {
            User user = (User) session.getAttribute(Constants.SESSION_USER);
            if (user == null) {
                return Result.error("请先登录");
            }
            
            Object stats = gameService.getUserGameStats(user.getId());
            return Result.success(stats);
        } catch (Exception e) {
            return Result.error("获取统计失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取用户道具列表
     */
    @GetMapping("/items")
    @ResponseBody
    public Result<Map<String, Integer>> getUserItems(HttpSession session) {
        try {
            User user = (User) session.getAttribute(Constants.SESSION_USER);
            if (user == null) {
                return Result.error("请先登录");
            }
            
            Map<String, Integer> items = itemService.getUserItems(user.getId());
            return Result.success(items);
        } catch (Exception e) {
            return Result.error("获取道具失败：" + e.getMessage());
        }
    }
    
    /**
     * 使用道具
     */
    @PostMapping("/use-item")
    @ResponseBody
    public Result<Integer> useItem(@RequestParam String itemCode, HttpSession session) {
        try {
            User user = (User) session.getAttribute(Constants.SESSION_USER);
            if (user == null) {
                return Result.error("请先登录");
            }
            
            boolean success = itemService.useItem(user.getId(), itemCode);
            if (success) {
                int remainCount = itemService.getItemCount(user.getId(), itemCode);
                return Result.success("使用成功", remainCount);
            } else {
                return Result.error("道具数量不足");
            }
        } catch (Exception e) {
            return Result.error("使用失败：" + e.getMessage());
        }
    }
}

